package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;
import com.ruoyi.system.domain.SysDictData;
import com.ruoyi.system.utils.DictUtils;
import org.apache.commons.io.FileUtils;
import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.drafts.Draft;
import org.java_websocket.framing.Framedata;
import org.java_websocket.handshake.ServerHandshake;
import org.java_websocket.drafts.Draft_6455;

import java.io.File;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NewBBwebsocket extends WebSocketClient {

    static Map<String,String> clentMap = new HashMap();
    //不带cookie认证
    public NewBBwebsocket(URI serverUri , Draft draft ) {
        super( serverUri, draft );
    }

    public NewBBwebsocket( URI serverURI ) {
        super( serverURI );
    }

    //带cookie认证时，用map
    public NewBBwebsocket(URI serverUri, Draft draft, Map<String, String> headers, int timeout) {
        super( serverUri, draft, headers, timeout );
    }


    @Override
    public void onOpen( ServerHandshake handshakedata ) {
        System.out.println( "开流--opened connection" );
    }

    @Override
    public void onMessage( String message ) {
        JSONObject mes = JSON.parseObject(message);
        clentMap.put(mes.getString("rid"),message);

    }

    @Override
    public void onClose( int code, String reason, boolean remote ) {
        System.out.println( "关流--Connection closed by " + ( remote ? "remote peer" : "us" ) );
    }

    @Override
    public void onError( Exception ex ) {
        ex.printStackTrace();

    }

    //NEWbb
    public static JSONObject get_newbb_content(String sport) {
        Integer sport_id = null;
        if(sport.equals("lol")){
            sport_id = 77;
        }
        if(sport.equals("cs")){
            sport_id = 75;
        }
        if(sport.equals("dota")){
            sport_id = 76;
        }
        /*String newBB_host = DictUtils.getDictCache("pl_rest_url").get(3).getDictValue();
        //用来发送的json数据
        List<SysDictData> sendList = DictUtils.getDictCache("newBB_send");
        Map send_getSession = JSON.parseObject(sendList.get(0).getRemark());
        Map send_getAll = JSON.parseObject(sendList.get(1).getRemark());
        Map send_getContent = JSON.parseObject(sendList.get(2).getRemark());*/
        String newBB_host = "wss://as-swarm-bbin-ws.betintegration.com/";
        //用来发送的json数据
//        List<SysDictData> sendList = DictUtils.getDictCache("newBB_send");
        JSONObject send_getSession = JSON.parseObject("{\"command\":\"request_session\",\"params\":{\"language\":\"zhh\",\"site_id\":\"510\",\"release_date\":\"11/03/2022-13:33\"},\"rid\":\"16482646455121\"}");
        JSONObject send_getAll = JSON.parseObject("{\"command\":\"get\",\"params\":{\"source\":\"betting\",\"what\":{\"game\":[[\"id\",\"team1_name\",\"team2_name\",\"team1_id\",\"team2_id\",\"team1_reg_name\",\"team2_reg_name\",\"info\",\"start_ts\",\"type\",\"text_info\",\"is_blocked\",\"markets_count\",\"stats\",\"strong_team\",\"is_neutral_venue\",\"is_stat_available\",\"video_provider\",\"show_type\",\"tv_info\"]],\"market\":[\"base\",\"id\",\"name\",\"order\",\"sequence\",\"show_type\",\"display_key\",\"display_sub_key\",\"type\",\"home_score\",\"away_score\",\"main_order\"],\"event\":[\"name\",\"id\",\"base\",\"type\",\"type_1\",\"price\",\"show_type\",\"home_value\",\"away_value\"],\"competition\":[\"name\"]},\"where\":{\"sport\":{\"id\":76},\"game\":{\"@or\":[{\"type\":{\"@in\":[0,2]}},{\"visible_in_prematch\":1}]},\"market\":{\"@or\":[{\"display_key\":\"OUTRIGHT\"},{\"display_key\":\"TOTALS\",\"main_order\":1},{\"display_key\":\"HANDICAP\",\"main_order\":1},{\"display_key\":\"WINNER\"},{\"display_key\":\"ODD/EVEN\"}]}},\"subscribe\":true},\"rid\":\"164878011410125\"}");
        JSONObject send_getContent = JSON.parseObject("{\"command\":\"get\",\"params\":{\"source\":\"betting\",\"what\":{\"game\":[[\"id\",\"show_type\",\"markets_count\",\"start_ts\",\"is_live\",\"is_blocked\",\"is_neutral_venue\",\"team1_id\",\"team2_id\",\"game_number\",\"text_info\",\"is_stat_available\",\"type\",\"info\",\"team1_name\",\"team2_name\",\"tv_info\"]],\"market\":[\"id\",\"col_count\",\"type\",\"sequence\",\"point_sequence\",\"express_id\",\"cashout\",\"display_key\",\"display_sub_key\",\"group_id\",\"name\",\"group_name\",\"order\",\"group_order\",\"extra_info\",\"name_template\",\"is_new\"],\"event\":[\"order\",\"id\",\"type_1\",\"type\",\"type_id\",\"original_order\",\"name\",\"price\",\"base\",\"home_value\",\"away_value\",\"display_column\"]},\"where\":{\"game\":{\"id\":19620845},\"sport\":{\"id\":77}},\"subscribe\":true},\"rid\":\"164878018953313\"}");
        Integer count = 1;
        JSONObject allMatch = new JSONObject();
        try {
            //没有cookie时
            NewBBwebsocket c = new NewBBwebsocket( new URI( newBB_host ));
            c.connect();
            while(!c.getReadyState().equals(READYSTATE.OPEN)){
                Thread.sleep(10);
            }
            //注册session
            String rid_getSession = System.currentTimeMillis()+""+(count++);
            clentMap.put(rid_getSession,null);
            send_getSession.put("rid",rid_getSession);
            c.send(JSONObject.toJSONString(send_getSession));
            while (clentMap.get(rid_getSession)==null){
                Thread.sleep(10);
            }
            //获取所有
            String rid_getAll = System.currentTimeMillis()+""+(count++);
            clentMap.put(rid_getAll,null);
            send_getAll.put("rid",rid_getAll);
            JSONPath.set(send_getAll,"params.subscribe",(Object)false);
            JSONPath.set(send_getAll,"params.where.sport.id",sport_id);
            c.send(JSONObject.toJSONString(send_getAll));
            System.out.println(JSONObject.toJSONString(send_getAll));
            while (clentMap.get(rid_getAll)==null){
                Thread.sleep(10);
            }
            //解析
            JSONObject all = JSON.parseObject(clentMap.get(rid_getAll));
            JSONObject competition = all.getJSONObject("data").getJSONObject("data").getJSONObject("competition");
            //将各个赛场的比赛集合到一起
            for (Object key:competition.keySet()) {
               allMatch.putAll(competition.getJSONObject(key.toString()).getJSONObject("game"));
            }
            for (Object g:allMatch.keySet()) {
                //获取详情
                String rid_getContet = System.currentTimeMillis()+""+(count++);
                clentMap.put(rid_getContet,null);
                send_getContent.put("rid",rid_getContet);
                JSONPath.set(send_getContent,"params.subscribe",(Object)false);
                JSONPath.set(send_getContent,"params.where.sport.id",sport_id);
                JSONPath.set(send_getContent,"params.where.game.id",Integer.parseInt(g.toString()));
                c.send(JSONObject.toJSONString(send_getContent));
                System.out.println(JSONObject.toJSONString(send_getContent));
                while (clentMap.get(rid_getContet)==null){
                    Thread.sleep(10);
                }
                JSONObject game = JSONObject.parseObject(clentMap.get(rid_getContet)).getJSONObject("data").getJSONObject("data").getJSONObject("game");
                allMatch.putAll(game);

            }
            //接收数据中，时间到了手动关闭连接，否则有可能一直接收消息
            c.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return allMatch;
    }
    public static JSONObject getAllGamesAllMatch(){
        JSONObject allGames = new JSONObject();
        List<String> games = new ArrayList();
        games.add("lol");
        games.add("dota");
        games.add("cs");
        for (String game:games) {
            JSONObject allMatch = get_newbb_content(game);
            allGames.put(game,allMatch);
        }
        return allGames;
    }
    public static void main(String[] args) throws Exception {
       /* ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i=0;i<100;i++) {
            int i2 = i;
            executorService.execute(new Runnable(){
                @Override
                public void run() {
                    System.out.println("启动:"+i2);
                }
            });
        }*/
       Long before = System.currentTimeMillis();
        JSONObject allGamesAllMatch = getAllGamesAllMatch();
//        JSONObject allGamesAllMatch = get_newbb_content("lol");
        System.out.println(System.currentTimeMillis()-before);
        System.out.println(allGamesAllMatch.size());

    }

/*

    public static void main(String[] args) throws Exception {
        get_newbb_content("lol");
        try {
            //用来发送的json数据，我这里将它放在一个文档里读取
//            String input = FileUtils.readFileToString(new File("src/main/resources/test.json"), "UTF-8");
            String test = "{\"command\":\"request_session\",\"params\":{\"language\":\"zhh\",\"site_id\":\"510\",\"release_date\":\"11/03/2022-13:15\"},\"rid\":\"16484637734071\"}";
            JSONObject jsonObject = JSONObject.parseObject(test);
//            net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(input);

            //需要cookie时，用map存储cookie
            //Map<String, String> headers = new HashMap<String, String>();
            //headers.put("Cookie", "sso.xx.com=XX.6069xx988696471cbbc074caff1f8308;");

            //使用cookie时的实例，ws地址换成自己的
            //Testwebsocket c = new Testwebsocket( new URI( "ws://test.xx.com:3000/dashboard/web/test/" ), new Draft_6455(), headers,  10000);

            //没有cookie时
            NewBBwebsocket c = new NewBBwebsocket( new URI( "wss://as-swarm-bbin-ws.betintegration.com/" ));

            c.connect();

            while(!c.getReadyState().equals(READYSTATE.OPEN)){

                Thread.sleep(10);
                System.out.println(c.getReadyState());
            }
            System.out.println("连接打开了！");
//            c.send("测试");

            c.send(jsonObject.toString());   //发送json数据


            //接收数据中，时间到了手动关闭连接，否则有可能一直接收消息
            Thread.sleep(1000);
            c.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
*/


}